
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function http({ url, data={}, dataForm = {}, method = 'POST', success, fail, revertBack } = {}) {
  const openId = wx.getStorageSync('userInfo').openId;
  const sessionId =wx.getStorageSync('userInfo').sessionId;
  let str = '';
  for (var item in dataForm) {
  str = str + '&' + item + '=' + dataForm[item]
  }
  var api = sessionId ? url + '?openId=' + openId + '&sessionId=' + sessionId : url + '?openId=' + openId;
  var url = str ? api + str : api;
    console.log(sessionId)
  wx.request({
  url: url,
  data: data,
  header: { 'content-type': 'application/json' },
      // header: { 'content-type':'multipart/form-data'},
  method,
  success: (res)=> {
  if (res.data.status == '200') {
  success && success(res.data);
  }
  else if (res.data.status == '401') {
  let appInstance = getApp();
  appInstance.login(revertBack);
  }
  else {
  fail && fail(res.data);
  }
  },
  fail: function (res) {
  // 请求失败，错误处理 
  // errorHander(res);
  }
  })
  }

function post({ url, data = {},dataForm = {},header, success, fail ,complete} = {}) {
	const sessionId = wx.getStorageSync('userInfo').sessionId;
  console.log('sessionId:'+sessionId);
	let str = '';
  for (var item in dataForm) {
  str = str + '&' + item + '=' + dataForm[item]
	}
	var api =url + '?sessionId=' + sessionId
  var url = str ? api + str : api;
	wx.request({
		url: url,
		data: data,
    header: header || {"Accept": "*/*"},
    method: 'POST',
		success: (res) => {
      
			if (res.data.status == '200') {
				
			}
			else if (res.data.status == '401') {
        wx.showToast({
          title: '登录已过期,请重新登陆',
          icon:'none',
          duration: 1500
        })
        wx.clearStorageSync();
				wx.navigateTo({
				  url: '../login/login',
				})
				// let appInstance = getApp();
				// appInstance.wxLogin(revertBack);
			}
      else if(res.data.status == '500'){
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
      }
			else {
				fail && fail(res.data);
			}
      success && success(res.data);
		},
		fail: function (res) { // 请求失败，错误处理 
			// errorHander(res);
      fail && fail(res);
		},
		complete:function(res){
			complete;
		}
	})
}

function get({ url, dataForm = {}, success, fail, revertBack } = {}) {
	const sessionId = wx.getStorageSync('sessionId');
	// url = url + '?sessionId=' + sessionId;
	let str = '';
	for (var item in dataForm) {
		str = str + '&' + item + '=' + dataForm[item]
	}
	var api = sessionId ? url + '?sessionId=' + sessionId : url + '?openId=' + openId;
	var url = str ? api + str : api;
	wx.request({
		url: url,
		header: { 'content-type': 'application/json' },
		method: 'GET',
		success: (res) => {
			if (res.data.status == '200') {
				success && success(res.data);
			}
			else if (res.data.status == '401') {
				// wx.navigateTo({
				//   url: '/page/login/login/index',
				// })
				let appInstance = getApp();
				appInstance.wxLogin(revertBack);
			}
			else {
				fail && fail(res.data);
			}
		},
		fail: function (res) { // 请求失败，错误处理 
			// errorHander(res);
		}
	})
}

function del({ url, success, fail, revertBack } = {}) {
	const sessionId = wx.getStorageSync('sessionId');
	url = url + '?sessionId=' + sessionId;
	wx.request({
		url: url,
		header: { 'content-type': 'application/json' },
		method: 'DELETE',
		success: (res) => {
			if (res.data.status == '200') {
				success && success(res.data);
			}
			else if (res.data.status == '401') {
				let appInstance = getApp();
				appInstance.wxLogin(revertBack);
			}
			else {
				fail && fail(res.data);
			}
		},
		fail: function (res) { // 请求失败，错误处理 
			// errorHander(res);
		}
	})
}

function restpost({ url, data = {}, success, fail, revertBack } = {}) {
	const sessionId = wx.getStorageSync('sessionId');
	console.log('----',url);
	wx.request({
		url: url,
		data: data,
		header: { 'content-type': 'application/json' },
		method: 'POST',
		success: (res) => {
			if (res.data.code == '200') {
				success && success(res.data.data);
			}
			else if (res.data.code == '401') {
				// wx.navigateTo({
				//   url: '/page/login/login/index',
				// })
				let appInstance = getApp();
				appInstance.wxLogin(revertBack);
			}
			else {
				fail && fail(res.data);
			}
		},
		fail: function (res) { // 请求失败，错误处理 
			// errorHander(res);
		}
	})
}

function initChart(canvas, width, height,option) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(chart);
  chart.setOption(option);
  return chart;
}

function getQueryString(url, name) {
	console.log("url = " + url)
	console.log("name = " + name)
	var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
	var r = url.substr(1).match(reg)
	if (r != null) {
		console.log("r = " + r)
		console.log("r[2] = " + r[2])
		return r[2]
	}
	return null;
}

 function login() {
  // wx.showLoading({ title: '登录中...' })
  var that = this;
  wx.getSetting({
    success: res => {
      if (!res.authSetting['scope.userInfo']) {
        wx.navigateTo({
          url: '../getSet/getSet',
        })
      }
    }
  })
  wx.login({ //login流程
    success: (res) => { //登录成功 
      console.log(res);
      if (res.code) {
        let code = res.code;
        wx.request({
          url: "https://groomtea.icebartech.com/api/miniApp/salesman/acquireOpenId?code=" + code,
          method: 'POST',
          success: (res) => {
            console.log(res);
            if (res.data.status == 200) {
              let openId = res.data.data.bussData;
              wx.setStorageSync("openId", openId);
              console.log(wx.getStorageSync("openId"))
            } else { console.log(res.data.status) }
          },
          fail: (err) => {
            console.log(err)
          }
        })
      } else {
        console.log('获取用户登录态失败！' + res)
      }

    }
  })
}

    
//上传图片
function uploadImage({tempFilePath,tempFile,success,fail}={}) {
       
}


module.exports = {
  login:login,
  formatTime: formatTime,
  formatNumber:formatNumber,
  http:http,
	post:post,
	get: get,
	del:del,
	restpost: restpost,
	getQueryString: getQueryString,
  upImg: uploadImage
}
